package com.bestom.waterquality.logic;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;

import com.bestom.waterquality.R;
import com.bestom.waterquality.WaterQualityApplication;
import com.bestom.waterquality.entity.Constant;
import com.bestom.waterquality.entity.RealBean;
import com.bestom.waterquality.listener.IGetMessageCallBack;
import com.bestom.waterquality.services.MQTTService;
import com.bestom.waterquality.services.MQTTService2;
import com.bestom.waterquality.services.MyServiceConnection;
import com.bestom.waterquality.services.MyServiceConnection2;
import com.bestom.waterquality.sql.DbManage;
import com.bestom.waterquality.util.DataTurn;
import com.bestom.waterquality.util.SharedPreferencesUtil;
import com.bestom.waterquality.util.ToastUtil;
import com.suke.widget.SwitchButton;

import org.eclipse.paho.client.mqttv3.MqttException;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import android_serialport_api.SerialPort;

/**
 * MQtt 配置
 */
public class MQttConfiguration implements IGetMessageCallBack {

    private static final String TAG = "MQttConfiguration";
    private MQttConfiguration() { }

    private static MQttConfiguration _instance = null;

    public static MQttConfiguration getInstance() {
        if (_instance == null)
            _instance = new MQttConfiguration();
        return _instance;
    }

    private SwitchButton mtSwitch1;
    private SwitchButton mtSwitch2;

    private EditText theme1;
    private EditText ipMt1;
    private EditText port1;
    private EditText mtDeviceId1;
    private EditText mtUser1;
    private EditText mtPassword1;
    private EditText period1;

    private EditText theme2;
    private EditText ipMt2;
    private EditText port2;
    private EditText mtDeviceId2;
    private EditText mtUser2;
    private EditText mtPassword2;
    private EditText period2;

    private String themeValue1 = "";
    private String ipMtValue1;
    private String portValue1;
    private String mtDeviceIdValue1;
    private String mtUserValue1;
    private String mtPasswordValue1;
    private String periodValue1;
    private String themeValue2;
    private String ipMtValue2;
    private String portValue2;
    private String mtDeviceIdValue2;
    private String mtUserValue2;
    private String mtPasswordValue2;
    private String periodValue2;

    private static boolean flag = false;
    private static boolean flag2 = false;

    private Context mContext;

    public void setDataAndListen(Context context, View view){
        if (mContext == null){
            mContext = context;
            //WaterQualityApplication.getApplication().controlKeyboardLayout(view.findViewById(R.id.mt_root),view.findViewById(R.id.mt_scroll));

            setBeforeValue1();
            setBeforeValue2();
            theme1 = view.findViewById(R.id.theme_1);
            ipMt1 = view.findViewById(R.id.ip_mt_1);
            port1 = view.findViewById(R.id.port_1);
            mtDeviceId1 = view.findViewById(R.id.mt_device_id_1);
            mtUser1 = view.findViewById(R.id.mt_user_1);
            mtPassword1 = view.findViewById(R.id.mt_password_1);
            period1 = view.findViewById(R.id.period_1);

            theme2 = view.findViewById(R.id.theme_2);
            ipMt2 = view.findViewById(R.id.ip_mt_2);
            port2 = view.findViewById(R.id.port_2);
            mtDeviceId2 = view.findViewById(R.id.mt_device_id_2);
            mtUser2 = view.findViewById(R.id.mt_user_2);
            mtPassword2 = view.findViewById(R.id.mt_password_2);
            period2 = view.findViewById(R.id.period_2);

            theme1.setText(themeValue1);
            ipMt1.setText(ipMtValue1);
            port1.setText(portValue1);
            mtDeviceId1.setText(mtDeviceIdValue1);
            mtUser1.setText(mtUserValue1);
            mtPassword1.setText(mtPasswordValue1);
            period1.setText(periodValue1);

            theme2.setText(themeValue2);
            ipMt2.setText(ipMtValue2);
            port2.setText(portValue2);
            mtDeviceId2.setText(mtDeviceIdValue2);
            mtUser2.setText(mtUserValue2);
            mtPassword2.setText(mtPasswordValue2);
            period2.setText(periodValue2);

            view.findViewById(R.id.save_set1).setOnClickListener(v -> new AlertDialog.Builder(mContext)
                    .setTitle(R.string.save)
                    .setMessage(R.string.save_message)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> {
                        if (!theme1.getText().toString().trim().equals(themeValue1)) SharedPreferencesUtil.getInstance().putValue(Constant.themeSP1,theme1.getText().toString().trim());
                        if (!ipMt1.getText().toString().trim().equals(ipMtValue1)) SharedPreferencesUtil.getInstance().putValue(Constant.ipMtSP1,ipMt1.getText().toString().trim());
                        if (!port1.getText().toString().trim().equals(portValue1)) SharedPreferencesUtil.getInstance().putValue(Constant.portSP1,port1.getText().toString().trim());
                        if (!mtDeviceId1.getText().toString().trim().equals(mtDeviceIdValue1)) SharedPreferencesUtil.getInstance().putValue(Constant.mtDeviceIdSP1,mtDeviceId1.getText().toString().trim());
                        if (!mtUser1.getText().toString().trim().equals(mtUserValue1)) SharedPreferencesUtil.getInstance().putValue(Constant.mtUserSP1,mtUser1.getText().toString().trim());
                        if (!mtPassword1.getText().toString().trim().equals(mtPasswordValue1)) SharedPreferencesUtil.getInstance().putValue(Constant.mtPasswordSP1,mtPassword1.getText().toString().trim());
                        if (!period1.getText().toString().trim().equals(periodValue1)) SharedPreferencesUtil.getInstance().putValue(Constant.periodSPSP1,period1.getText().toString().trim());
                        setBeforeValue1();
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show());
            view.findViewById(R.id.save_set2).setOnClickListener(v -> new AlertDialog.Builder(mContext)
                    .setTitle(R.string.save)
                    .setMessage(R.string.save_message)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> {
                        if (!theme2.getText().toString().trim().equals(themeValue2)) SharedPreferencesUtil.getInstance().putValue(Constant.themeSP2,theme2.getText().toString().trim());
                        if (!ipMt2.getText().toString().trim().equals(ipMtValue2)) SharedPreferencesUtil.getInstance().putValue(Constant.ipMtSP2,ipMt2.getText().toString().trim());
                        if (!port2.getText().toString().trim().equals(portValue2)) SharedPreferencesUtil.getInstance().putValue(Constant.portSP2,port2.getText().toString().trim());
                        if (!mtDeviceId2.getText().toString().trim().equals(mtDeviceIdValue2)) SharedPreferencesUtil.getInstance().putValue(Constant.mtDeviceIdSP2,mtDeviceId2.getText().toString().trim());
                        if (!mtUser2.getText().toString().trim().equals(mtUserValue2)) SharedPreferencesUtil.getInstance().putValue(Constant.mtUserSP2,mtUser2.getText().toString().trim());
                        if (!mtPassword2.getText().toString().trim().equals(mtPasswordValue2)) SharedPreferencesUtil.getInstance().putValue(Constant.mtPasswordSP2,mtPassword2.getText().toString().trim());
                        if (!period2.getText().toString().trim().equals(periodValue2)) SharedPreferencesUtil.getInstance().putValue(Constant.periodSPSP2,period2.getText().toString().trim());
                        setBeforeValue2();
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show());
            view.findViewById(R.id.reset1).setOnClickListener(v -> new AlertDialog.Builder(mContext)
                    .setTitle(R.string.reset)
                    .setMessage(R.string.reset_message)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> setDefValue1())
                    .setNegativeButton(R.string.cancel, null)
                    .show());
            view.findViewById(R.id.reset2).setOnClickListener(v -> new AlertDialog.Builder(mContext)
                    .setTitle(R.string.reset)
                    .setMessage(R.string.reset_message)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> setDefValue2())
                    .setNegativeButton(R.string.cancel, null)
                    .show());
            mtSwitch1 = view.findViewById(R.id.mt_1_switch);
            mtSwitch1.setOnCheckedChangeListener((view12, isChecked) -> {
                if (isChecked) {
                    startMQttService1();
                    WaterQualityApplication.mtIsOk = true;
                }else {
                    WaterQualityApplication.mtIsOk = false;
                    if (flag){
                        if (mHandler1 != null){
                            mHandler1.removeCallbacksAndMessages(null);
                            mHandler1 = null;
                        }
                        if (MQTTService.client != null && MQTTService.client.isConnected()){
                            try {
                                MQTTService.client.disconnect();
                            } catch (MqttException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
            mtSwitch2 = view.findViewById(R.id.mt_2_switch);
            mtSwitch2.setOnCheckedChangeListener((view1, isChecked) -> {
                if (isChecked) {
                    startMQttService2();
                    WaterQualityApplication.mt2IsOk = true;
                }else {
                    WaterQualityApplication.mt2IsOk = false;
                    if (flag2){
                        if (mHandler2 != null){
                            mHandler2.removeCallbacksAndMessages(null);
                            mHandler2 = null;
                        }
                        if (MQTTService2.client != null && MQTTService2.client.isConnected()){
                            try {
                                MQTTService2.client.disconnect();
                            } catch (MqttException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
        }
    }

    /**开启第一个MQtt*/
    private void startMQttService1(){
        MyServiceConnection serviceConnection1 = new MyServiceConnection();
        MQTTService.setConnectInfo(mContext, themeValue1,ipMtValue1,portValue1,mtDeviceIdValue1,mtUserValue1,mtPasswordValue1,this);
        Intent intent = new Intent(mContext, MQTTService.class);
        mContext.bindService(intent, serviceConnection1, Context.BIND_AUTO_CREATE);
    }
    /**开启第二个MQtt*/
    private void startMQttService2(){
        MyServiceConnection2 serviceConnection2 = new MyServiceConnection2();
        MQTTService2.setConnectInfo(mContext, themeValue2,ipMtValue2,portValue2,mtDeviceIdValue2,mtUserValue2,mtPasswordValue2, this);
        Intent intent = new Intent(mContext, MQTTService2.class);
        mContext.bindService(intent, serviceConnection2, Context.BIND_AUTO_CREATE);
    }

    /**获取上次保存的第一个MQTT配置的值*/
    private void setBeforeValue1(){
        mtDeviceIdValue1 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.mtDeviceIdSP1, Constant.defDeviceId);
        themeValue1 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.themeSP1,Constant.defTheme);
        ipMtValue1 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.ipMtSP1,Constant.defIpMt);
        portValue1 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.portSP1,Constant.defPort);
        mtUserValue1 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.mtUserSP1,Constant.defUser);
        mtPasswordValue1 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.mtPasswordSP1,Constant.defPassword);
        periodValue1 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.periodSPSP1,Constant.defPeriod);
    }
    /**获取上次保存的第二个MQTT配置的值*/
    private void setBeforeValue2(){
        mtDeviceIdValue2 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.mtDeviceIdSP2, Constant.defDeviceId);
        themeValue2 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.themeSP2,Constant.defTheme);
        ipMtValue2 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.ipMtSP2,Constant.defIpMt);
        portValue2 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.portSP2,Constant.defPort);
        mtUserValue2 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.mtUserSP2,Constant.defUser);
        mtPasswordValue2 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.mtPasswordSP2,Constant.defPassword);
        periodValue2 = (String) SharedPreferencesUtil.getInstance().getValue(Constant.periodSPSP2,Constant.defPeriod);
    }
    /**重置第一个MQTT配置的值*/
    private void setDefValue1(){
        SharedPreferencesUtil.getInstance().putValue(Constant.themeSP1,Constant.defTheme);
        SharedPreferencesUtil.getInstance().putValue(Constant.ipMtSP1,Constant.defIpMt);
        SharedPreferencesUtil.getInstance().putValue(Constant.portSP1,Constant.defPort);
        SharedPreferencesUtil.getInstance().putValue(Constant.mtDeviceIdSP1,Constant.defDeviceId);
        SharedPreferencesUtil.getInstance().putValue(Constant.mtUserSP1,Constant.defUser);
        SharedPreferencesUtil.getInstance().putValue(Constant.mtPasswordSP1,Constant.defPassword);
        SharedPreferencesUtil.getInstance().putValue(Constant.periodSPSP1,Constant.defPeriod);

        theme1.setText(Constant.defTheme);
        ipMt1.setText(Constant.defIpMt);
        port1.setText(Constant.defPort);
        mtDeviceId1.setText(Constant.defDeviceId);
        mtUser1.setText(Constant.defUser);
        mtPassword1.setText(Constant.defPassword);
        period1.setText(Constant.defPeriod);
    }
    /**重置第二个MQTT配置的值*/
    private void setDefValue2(){
        SharedPreferencesUtil.getInstance().putValue(Constant.themeSP2,Constant.defTheme);
        SharedPreferencesUtil.getInstance().putValue(Constant.ipMtSP2,Constant.defIpMt);
        SharedPreferencesUtil.getInstance().putValue(Constant.portSP2,Constant.defPort);
        SharedPreferencesUtil.getInstance().putValue(Constant.mtDeviceIdSP2,Constant.defDeviceId);
        SharedPreferencesUtil.getInstance().putValue(Constant.mtUserSP2,Constant.defUser);
        SharedPreferencesUtil.getInstance().putValue(Constant.mtPasswordSP2,Constant.defPassword);
        SharedPreferencesUtil.getInstance().putValue(Constant.periodSPSP2,Constant.defPeriod);

        theme2.setText(Constant.defTheme);
        ipMt2.setText(Constant.defIpMt);
        port2.setText(Constant.defPort);
        mtDeviceId2.setText(Constant.defDeviceId);
        mtUser2.setText(Constant.defUser);
        mtPassword2.setText(Constant.defPassword);
        period2.setText(Constant.defPeriod);
    }

    @Override
    public void setSuccess(String mt, String str1) {
        ToastUtil.toast("Mqtt connect" + str1);
        if (mt.equals("1")){
            flag = true;
            // 若用户设置为0，那么强制定时为30分钟
            int i = Integer.parseInt(periodValue1);
            if (i == 0){
                i = 30;
            }
            long time = i*60*1000;
            if (mHandler1 == null){
                //开启定时上报实时数据
                mHandler1 = new Handler();
                mHandler1.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder stringBuilder = DbManage.getInstance(mContext).getToMtData();
//                        String[] split = stringBuilder.toString().split("---");
                        if (flag) {
                            String timeStr1 = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                            String path = "";
                            long millis = System.currentTimeMillis();
                            if (RTSPSet.getInstance().SnapPicture(Constant.realImageDir, millis))
                                path = millis + ".jpg";

                            //可能因为存储空间不足或者其他原因导致图片未拍摄保存成功，所以做判断如果文件不存在
                            if (!path.isEmpty() && !new File(Constant.realImageDir + path).exists()) path = "";
                            DbManage.getInstance(mContext).addRealRecord(timeStr1, SerialPortSet.getInstance().getRealVcp(), SerialPortSet.getInstance().getRealTemp(), path);

                            RealBean bean = new RealBean(timeStr1, SerialPortSet.getInstance().getRealVcp(), SerialPortSet.getInstance().getRealTemp(), path);
                            ImageViewer.getInstance().addRealData(bean);
//                            MQTTService.publish(Constant.DataPublishTopic,"01", split[0], split.length > 1 ? split[1] : "");
                            MQTTService.publish(Constant.DataPublishTopic,"01", stringBuilder.toString(), path.isEmpty() ? path : Constant.realImageDir + path);
                        }
                        if (flag && mHandler1 != null){
                            int i = Integer.parseInt(periodValue1);
                            if (i == 0){
                                i = 30;
                            }
                            long time = i*60*1000;
                            mHandler1.postDelayed(this, time);
                        }
                    }
                }, time);
            }

        }else {
            flag2 = true;
            // 若用户设置为0，那么强制定时为30分钟
            int i = Integer.parseInt(period2.getText().toString());
            if (i == 0){
                i = 30;
            }
            long time = i*60*1000;
            if (mHandler2 == null){
                //开启定时上报实时数据
                mHandler2 = new Handler();
                mHandler2.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder stringBuilder = DbManage.getInstance(mContext).getToMtData();
//                        String[] split = stringBuilder.toString().split("---");
                        if (flag2) {

                            String timeStr1 = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                            String path = "";
                            long millis = System.currentTimeMillis();
                            if (RTSPSet.getInstance().SnapPicture(Constant.realImageDir, millis))
                                path = millis + ".jpg";

                            //可能因为存储空间不足或者其他原因导致图片未拍摄保存成功，所以做判断如果文件不存在
                            if (!path.isEmpty() && !new File(Constant.realImageDir + path).exists()) path = "";
                            DbManage.getInstance(mContext).addRealRecord(timeStr1, SerialPortSet.getInstance().getRealVcp(), SerialPortSet.getInstance().getRealTemp(), path);

                            RealBean bean = new RealBean(timeStr1, SerialPortSet.getInstance().getRealVcp(), SerialPortSet.getInstance().getRealTemp(), path);
                            ImageViewer.getInstance().addRealData(bean);

//                            MQTTService2.publish(Constant.DataPublishTopic,"01", split[0], split.length > 1 ? split[1] : "");
                            MQTTService2.publish(Constant.DataPublishTopic,"01", stringBuilder.toString(), path.isEmpty() ? path : Constant.realImageDir + path);
                        }
                        if (flag2 && mHandler2 != null){
                            int i = Integer.parseInt(periodValue2);
                            if (i == 0){
                                i = 30;
                            }
                            long time = i*60*1000;
                            mHandler2.postDelayed(this, time);
                        }
                    }
                }, time);
            }
        }

    }
    private Handler mHandler1;
    private Handler mHandler2;

    @Override
    public void setFail(String mt, String str1) {
        if (mt.equals("1")){
            if (str1.equals("net")){
                ToastUtil.toast("连接失败，请检查网络！");
                flag = false;
                if (mtSwitch1.isChecked()) mtSwitch1.setChecked(false);
            }
        }else {
            if (str1.equals("net")){
                ToastUtil.toast("连接失败，请检查网络！");
                flag2 = false;
                if (mtSwitch2.isChecked()) mtSwitch2.setChecked(false);
            }
        }
    }

    @Override
    public void setMessage(String mt, String str1) {

    }
}
